package com.houserent.service;

import com.houserent.domain.House;

/**
 *【业务层】
 * 1.相应 HouseView 的调用
 * 2.完成对房屋信息的各种操作
 */
public class HouseService {

    private House[] houses;//保存 House 对象
    private int houseNum = 1;//记录房屋数量
    private int idCounter = 1;//记录当前的 id 增长到哪个值


    public int getCount() {
        return houseNum;
    }

    public void setCount(int count) {
        this.houseNum = count;
    }

    public HouseService(int size) {
        houses = new House[size];//当创建 HouseService 对象时指定数组大小
        //为了配合列表测试信息，初始化一个 House 对象
        houses[0] = new House(1, "jack", "112", "北京", 1000, "未出租");
    }

    //返回数组
    public House[] list() {
        return houses;
    }

    //添加新房源
    public boolean add(House newHouse) {
        //判断是否还可以继续添加
        if (houseNum == houses.length) {
            System.out.println("数组已满，不能添加");
            return false;
        }

        //设置 newHouse id
        newHouse.setId(++idCounter);
        //先把 newHouse 对象加到数组，房屋数量再增加
        houses[houseNum++] = newHouse;
        return true;
    }

    //删除房源
    public boolean delet(int delId) {
        //遍历数组寻找要删除房屋下标并记录
        int index = -1;
        for (int i = 0; i < houseNum; i++) {
            if (houses[i].getId() == delId) {
                index = i;
                break;
            }
        }

        //判断是否有该房屋信息
        if (index == -1) {
            System.out.println("数组中无该id房屋");
            return false;
        }

        //删除该房屋信息(通过将其后的房屋信息依次赋给前一位)
        for (int i = index; i < houseNum; i++) {
            houses[i] = houses[i + 1];
        }
        houseNum--;
        return true;
    }

    //查找房屋信息并返回
    public House read(int readId) {
        //遍历数组，查找id
        for (int i = 0; i < houseNum; i++) {
            if (houses[i].getId() == readId) {
                return houses[i];
            }
        }

        //如果无该房屋信息，返回 null
        return null;
    }

    //修改房屋主人信息
    public void updateOwner(House house, String updateOwner) {
        house.setOwner(updateOwner);
    }

    //修改房屋电话信息
    public void updatePhone(House house, String updatePhone) {
        house.setPhone(updatePhone);
    }

    //修改房屋地址信息
    public void updateAddress(House house, String updateAddress) {
        house.setAddress(updateAddress);
    }

    //修改房屋月租信息
    public void updateRent(House house, int updateRent) {
        house.setRent(updateRent);
    }

    //修改房屋状态信息
    public void updateState(House house, String updateState) {
        house.setState(updateState);
    }

}